/*
 * Copyright (c) 2018, apexes.net. All rights reserved.
 *
 *         http://www.apexes.net
 *
 */
package net.apexes.commons.lunar;

import java.io.DataInputStream;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;

/**
 * 节气
 * 
 * @author HeDYn<hedyn@foxmail.com>
 */
public final class Solarterms {

	/**
	 * 返回节气序号，节气数组为：
	 * "小寒", "大寒", "立春", "雨水", "惊蛰", "春分",
	 * "清明", "谷雨", "立夏", "小满", "芒种", "夏至",
	 * "小暑", "大暑", "立秋", "处暑", "白露", "秋分",
	 * "寒露", "霜降", "立冬", "小雪", "大雪", "冬至"
	 * @param date
	 * @return
	 */
	public static int getSolartermIndex(Date date) {
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date);
		int year = calendar.get(Calendar.YEAR);
		int month = calendar.get(Calendar.MONTH);
		int day = calendar.get(Calendar.DAY_OF_MONTH);
		Integer v = Solartermsdat.INSTANCE.data(year, month);
		if (v != null) {
			int index = month * 2;
			if (((v >> 27) & 0x1f) == day) {
				return index;
			} else if (((v >> 11) & 0x1f) == day) {
				return index + 1;
			}
		}
		return -1;
	}
	
	public static Date getSolartermDate(int year, int index) {
		int month = index / 2;
		Integer v = Solartermsdat.INSTANCE.data(year, month);
		if (v != null) {
			int bit = 0;
			if ((index & 1) == 0) {
				bit = 16;
			}
			int day = v >> (11 + bit) & 0x1f;
			int hourOfDay = (v >> (6 + bit)) & 0x1f;
			int minute = (v >> bit) & 0x3f;
			Calendar calendar = Calendar.getInstance();
			calendar.set(year, month, day, hourOfDay, minute, 0);
			return calendar.getTime();
		}
		return null;
	}

}
